package test1;

import org.apache.http.*;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.util.LinkedList;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

public class HttpUtil {
    /**
     * 连接池中的最大连接数
     */
    private static final int MAX_CONN_TOTAL = 10;
    /**
     * 连接同一个route最大的并发数
     */
    private static int MAX_CONN_PER_ROUTE = 10;
    /**
     * 从连接池中获取可用连接最大超时时间 单位：毫秒
     */
    private static int CONNECT_REQUEST_TIMEOUT = 1000;
    /**
     * 连接目标url最大超时 单位：毫秒
     */
    private static int CONNECT_TIMEOUT = 1000;
    /**
     * 等待响应（读数据）最大超时 单位：毫秒
     */
    private static int SOCKET_TIMEOUT = 1000;

    /**
     * httpGet方法
     *
     * @param reqModel
     * @return
     * @throws URISyntaxException
     * @throws IOException
     */
    public static HttpResqModel httpGet(HttpReqModel reqModel) throws Exception {
        String url = reqModel.getUrl();
        if (Objects.isNull(url)) {
            throw new Exception("request httpGet Method url为空");
        }
        URIBuilder uriBuilder = new URIBuilder(url);
        //设置请求参数
        Map<String, String> params = reqModel.getParams();
        if (!CollectionUtils.isEmpty(params)) {
            LinkedList<NameValuePair> list = new LinkedList<>();
            Set<String> keySet = params.keySet();
            for (String k : keySet) {
                list.add(new BasicNameValuePair(k, params.get(k)));
            }
            uriBuilder.setParameters(list);
        }

        HttpGet httpGet = new HttpGet(uriBuilder.build());
        //设置请求头
        Map<String, String> header = reqModel.getHeader();
        if (!CollectionUtils.isEmpty(header)) {
            Set<String> keySet = header.keySet();
            for (String k : keySet) {
                httpGet.addHeader(k, header.get(k));
            }
        }
        //设置读取时间
        int socketTimeout = SOCKET_TIMEOUT;
        if (0 != reqModel.getReadTimeout()) {
            socketTimeout = reqModel.getReadTimeout();
        }
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectionRequestTimeout(CONNECT_REQUEST_TIMEOUT)
                .setConnectTimeout(CONNECT_TIMEOUT)
                .setSocketTimeout(socketTimeout)
                .build();

        HttpClient httpClient = HttpClientBuilder.create().setMaxConnTotal(MAX_CONN_TOTAL)
                .setMaxConnPerRoute(MAX_CONN_PER_ROUTE)
                .setDefaultRequestConfig(requestConfig)
                .build();

        HttpResponse httpResponse = null;
        try {
            //执行http请求
            httpResponse = httpClient.execute(httpGet);
        } catch (IOException e) {
            throw new IOException();
        }
        StatusLine statusLine = httpResponse.getStatusLine();
        HttpResqModel resqModel = new HttpResqModel();
        int statusCode = statusLine.getStatusCode();
        resqModel.setStatusCode(statusCode);

        //非200状态的处理
        if (HttpStatus.SC_OK != statusCode) {
            //throw new Excetion(statusCode, null);
            System.out.println(statusCode);
        }
        HttpEntity httpEntity = httpResponse.getEntity();
        String entity = null;
        try {
            entity = EntityUtils.toString(httpEntity, "utf-8");
        } catch (IOException e) {
            throw new Exception();
        }
        resqModel.setReturnMsg(entity);
        return resqModel;
    }

    /**
     * httpPost方法
     *
     * @param reqModel
     * @return
     */
    public static HttpResqModel httpPost(HttpReqModel reqModel) throws    Exception {
        String url = reqModel.getUrl();
        if (Objects.isNull(url)) {
            throw new Exception("request httpGet Method url为空");
        }
        HttpPost httpPost = new HttpPost(url);
        //设置post请求头
        Map<String, String> header = reqModel.getHeader();
        if (!CollectionUtils.isEmpty(header)) {
            Set<String> keySet = header.keySet();
            for (String k : keySet) {
                httpPost.addHeader(k, header.get(k));
            }
        }
        //设置参数
        Map<String, String> params = reqModel.getParams();
        if (!CollectionUtils.isEmpty(header)) {
            LinkedList<NameValuePair> pairs = new LinkedList<>();
            Set<String> keySet = params.keySet();
            for (String k : keySet) {
                pairs.add(new BasicNameValuePair(k,params.get(k)));
            }
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs,"utf-8");
            httpPost.setEntity(entity);
        }
        //设置读取时间
        int socketTimeout = SOCKET_TIMEOUT;
        if (0 != reqModel.getReadTimeout()) {
            socketTimeout = reqModel.getReadTimeout();
        }
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectionRequestTimeout(CONNECT_REQUEST_TIMEOUT)
                .setConnectTimeout(CONNECT_TIMEOUT)
                .setSocketTimeout(socketTimeout)
                .build();

        HttpClient httpClient = HttpClientBuilder.create().setMaxConnTotal(MAX_CONN_TOTAL)
                .setMaxConnPerRoute(MAX_CONN_PER_ROUTE)
                .setDefaultRequestConfig(requestConfig)
                .build();

        HttpResponse response = null;
        //执行http请求
        try {
            response = httpClient.execute(httpPost);
        } catch (IOException e) {
            e.printStackTrace();
        }

        StatusLine statusLine = response.getStatusLine();
        HttpResqModel resqModel = new HttpResqModel();
        int statusCode = statusLine.getStatusCode();
        resqModel.setStatusCode(statusCode);

        //非200状态的处理
        if (HttpStatus.SC_OK != statusCode) {
            throw new Exception(String.valueOf(statusCode), null);
        }
        HttpEntity httpEntity = response.getEntity();
        String entity = null;
        try {
            entity = EntityUtils.toString(httpEntity, "utf-8");
        } catch (IOException e) {
            throw new Exception();
        }
        resqModel.setReturnMsg(entity);
        return resqModel;
    }
}